import hashlib

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .service import addUser, verify, changePwd, getPwd
from .models import Users


# Create your views here.
def signup(request):
    return render(request, 'pages/user/signup.html')


def signin(request):
    me = request.COOKIES.get('me')
    if me:
        try:
            if getPwd(me.split('^')[0]) == me.split('^')[1]:
                return redirect(request, '/')
            else:
                return render(request, 'pages/user/signin.html')
        except:
            return render(request, 'pages/user/signin.html')
    else:
        return render(request, 'pages/user/signin.html')


def index(request):
    me = request.COOKIES.get('me')
    if me:
        try:
            if getPwd(me.split('^')[0]) == me.split('^')[1]:
                return render(request, 'awesome_spider/home.html')
            else:
                return render(request, 'pages/user/index.html')
        except:
            return render(request, 'pages/user/index.html')
    else:
        return render(request, 'pages/user/index.html')


def login(request):
    if request.method == 'POST':
        user = Users(username=request.POST['username'],
                     password=request.POST['password'])
        return verify(request, user=user)


def creatUser(request):
    if request.method == 'POST':
        user = Users(username=request.POST['username'],
                     password=hashlib.md5((str(request.POST['password']) + 'awesome_spider').encode()).hexdigest(),
                     email=request.POST['email'],
                     identity=request.POST['identity'])
        return addUser(request, user=user)


def changepwd(request):
    me = request.COOKIES.get('me')
    if me:
        try:
            if getPwd(me.split('^')[0]) == me.split('^')[1]:
                return render(request, 'pages/user/changepwd.html')
            else:
                return redirect(request, '/')
        except:
            return redirect(request, '/')
    else:
        return redirect(request, '/')


def changePassword(request):
    if request.method == 'POST':
        me = request.COOKIES.get('me')
        name = me.split('^')[0]
        a = changePwd(name, request.POST['origin'], request.POST['new'])
        if a['result']:
            res = HttpResponse({"<a href='/'>密码修改成功,点击返回</a>"})
            res.set_cookie('me',
                           f"{request.COOKIES.get('me').split('^')[0]}^{hashlib.md5((request.POST['new'] + 'awesome_spider').encode()).hexdigest()}")
            return res
        else:
            return HttpResponse({a['detail']})


def logout(request):
    res = HttpResponseRedirect('/signin')
    res.delete_cookie('me')
    return res
